<template>
  <div class="remindLayer">
    <span class="remindTitle" :style="remindSetStatus ? 'margin-bottom: 30px;' : ''">
      {{ parseSymbol(symbol, contract)[1].toUpperCase() }} / {{ parseSymbol(symbol, contract)[2].toUpperCase() }} {{$t('ndxStake.marketRemind')}}
    </span>
    <p class="newPrice" v-if="remindSetStatus">
      <span @click="handleChangePrice" style="cursor: pointer;">
        {{ $t('quotation.newPrice') }}：{{ toFixed(toNonExponential(parseFloat(symbolPrice)), priceDecimal) }}
        {{ parseSymbol(symbol, contract)[2].toUpperCase() }}
      </span>
    </p>
    <div class="remindPrice clearfix" v-if="!remindSetStatus">
      <span class="fl allRemind1" @click="handleChangePrice">
        {{ $t('quotation.newPrice') }}：{{ toFixed(toNonExponential(parseFloat(symbolPrice)), priceDecimal) }}
        {{ parseSymbol(symbol, contract)[2].toUpperCase() }}
      </span>
      <span class="fr allRemind" @click="handleToQuotation">{{$t('ndxStake.allReminders')}} ></span>
    </div>
    <div class="remindMain">
      <div class="contLeft">
        <div class="flexb setPrice">
          <label :style="$store.state.app.language === 'ko' ? 'text-align: center;' : ''">{{$t('ndxStake.priceHigh')}}</label>
          <el-input
            v-model="maxPrice"
            class="hideArrow"
            :class="{'borderRed': maxPriceVerification || maxPriceVeriError}"
            :placeholder="$t('ndxStake.inputPrice')"
            type="number"
            @blur="handleFormatNumber"
            @keyup.native="handleMaxVerification"
            title="">
            <span slot="suffix">{{ parseSymbol(symbol, contract)[2].toUpperCase() }}</span>
          </el-input>
          <span class="priceTip" v-if="maxPriceVeriError">{{$t('ndxStake.truePrice')}}</span>
          <span class="priceTip" v-else-if="maxPriceVerification">{{$t('ndxStake.noLowPrice')}}</span>
        </div>
        <div class="flexb setPrice">
          <label :style="$store.state.app.language === 'ko' ? 'text-align: center;' : ''">{{$t('ndxStake.priceLow')}}</label>
          <el-input
            v-model="minPrice"
            class="hideArrow"
            :class="{'borderRed': minPriceVerification}"
            :placeholder="$t('ndxStake.inputPrice')"
            type="number"
            @blur="handleFormatNumber"
            @keyup.native="handleMinVerification"
            title="">
            <span slot="suffix">{{ parseSymbol(symbol, contract)[2].toUpperCase() }}</span>
          </el-input>
          <span class="priceTip" v-if="minPriceVeriError">{{$t('ndxStake.truePrice')}}</span>
          <span class="priceTip" v-else-if="minPriceVerification">{{$t('ndxStake.noHighPrice')}}</span>
        </div>
      </div>
      <div class="contCenter">
        <span class="contCenterText">{{$t('ndxStake.volatility')}}</span>
        <div style="display: inline-block;">
          <el-tooltip placement="bottom" effect="light">
            <div slot="content" class="volatilityContent">
              <p>{{$t('ndxStake.inMinutes')}}</p>
              <p>{{$t('ndxStake.highLower')}}</p>
            </div>
            <div class="volatility">
              <i class="iconfont icon-jiaoyizanting"></i>
            </div>
          </el-tooltip>
        </div>
      </div>
      <div class="contRight">
        <div
          v-for="(item, index) in volatility"
          :key="index"
          :class="{'active': changeVolatility === index, 'noMargin': index === 2 || index === 5}"
          @click="handleChangeValue(index)">
          {{ item }}%
        </div>
      </div>
    </div>
    <div class="remindEmail flexb" v-if="!remindSetStatus">
      <span>{{$t('ndxStake.emailNotice')}}</span>
      <div v-if="$store.state.app.accountInfo && $store.state.app.accountInfo.email">
        <span>{{ $store.state.app.accountInfo.email }}</span>
        <span class="changeBtn" @click="handleToChangeEmail">{{$t('ndxStake.change')}}</span>
      </div>
      <div v-else>
        <span class="nobind">{{$t('ndxStake.noBindEmail')}}</span>
        <span class="changeBtn" @click="handleToChangeEmail" style="margin-left: 30px;">{{$t('ndxStake.bind')}}</span>
      </div>
    </div>
    <div class="comfirmBtn" v-if="!remindSetStatus">
      <!-- 条件三个值都为空、没绑定邮箱、剩余条数未零 -->
      <el-button type="primary" style="width: 220px;"
        @click="handleCreateRemind"
        :disabled="!RemindDisabled
        || !$store.state.app.accountInfo.remainMarketRemindCount
        || !$store.state.app.accountInfo.email
        || maxPriceVerification
        || minPriceVerification
        || maxPriceVeriError
        || minPriceVeriError">{{$t('ndxStake.createAccount')}}</el-button>
      <p v-if="!$store.state.app.accountInfo.remainMarketRemindCount" style="color: #EE1443;">
        {{$t('ndxStake.surplus', {number: $store.state.app.accountInfo.remainMarketRemindCount})}}
      </p>
    </div>
    <div class="comfirmBtn" style="margin-top: 30px;" v-else>
      <el-button type="primary" style="width: 220px;"
        @click="handleUpdateRemind"
        :disabled="!RemindDisabled
        || maxPriceVerification
        || minPriceVerification
        || maxPriceVeriError
        || minPriceVeriError">{{$t('ndxStake.saveAndModify')}}</el-button>
    </div>
  </div>
</template>

<script>
// import { EosModel } from '@/utils/eos';
import { authorized, toFixed, toNonExponential, parseSymbol } from '@/utils/validate';

export default {
  name: 'remindLayer', // 行情提醒弹窗
  components: {
  },
  data() {
    return {
      maxPrice: '', // 价格高于值
      minPrice: '', // 价格低于值
      volatility: ['10', '20', '30', '50', '80', '100'], // 波动率值
      changeVolatility: -1, // 波动率选中值
      changeVolatilityVal: '', // 波动率值
      accountId: '', // 行情提醒Id
      maxPriceVerification: false, // 最高价验证
      minPriceVerification: false, // 最低价验证
      maxPriceVeriError: false, // 输入负值验证
      minPriceVeriError: false, // 输入负值验证
    }
  },
  props: {
    // 1：更新提醒 0：增加提醒
    remindSetStatus: {
      type: Number,
      default: 0
    },
    symbolId: {
      type: Number,
      default: 0
    },
    symbol: {
      type: String,
      default: '',
    },
    remindSetVisible: {
      type: Boolean,
      default: false
    },
    symbolPrice: {
      type: String,
      default: ''
    },
    contract: {
      type: String,
      default: ''
    },
    priceDecimal: {
      type: Number,
      default: 0,
    },
    maxMinPrice: {
      type: Object,
    }
  },
  computed: {
    RemindDisabled() {
      return this.maxPrice || this.minPrice || this.changeVolatilityVal;
    },
  },
  watch: {
    remindSetVisible: function change(val) {
      this.maxPriceVerification = false;
      this.minPriceVerification = false;
      this.maxPriceVeriError = false;
      this.minPriceVeriError = false;

      if (val && this.remindSetStatus) {
        this.handleRemindData();
      } else {
        this.handleGetAccountInfo();
        this.maxPrice = '';
        this.minPrice = '';
        this.changeVolatility = -1;
        this.changeVolatilityVal = '';
      }
    }
  },
  created() {
  },
  mounted() {
    // 判断是修改还是新增 1：更新提醒 0：增加提醒
    if (this.remindSetStatus) {
      this.handleRemindData();
    } else {
      this.handleGetAccountInfo();
      this.maxPrice = '';
      this.minPrice = '';
      this.changeVolatility = -1;
      this.changeVolatilityVal = '';
    }
  },
  methods: {
    // 选择波动率
    handleChangeValue(val) {
      if (this.changeVolatility === val) {
        this.changeVolatility = -1;
        this.changeVolatilityVal = '';
        return;
      }
      this.changeVolatility = val;
      switch (val) {
        case 0:
          this.changeVolatilityVal = 10;
          break;
        case 1:
          this.changeVolatilityVal = 20;
          break;
        case 2:
          this.changeVolatilityVal = 30;
          break;
        case 3:
          this.changeVolatilityVal = 50;
          break;
        case 4:
          this.changeVolatilityVal = 80;
          break;
        case 5:
          this.changeVolatilityVal = 100;
          break;
        default:
          break;
      }
    },
    // 获取行情提醒数据
    handleRemindData() {
      this.maxPrice = this.maxMinPrice.maxPrice;
      this.minPrice = this.maxMinPrice.minPrice;
      this.accountId = this.maxMinPrice.id;
      const volatility = this.maxMinPrice.volatility;
      switch (volatility) {
        case 10:
          this.changeVolatility = 0;
          this.changeVolatilityVal = 10;
          break;
        case 20:
          this.changeVolatility = 1;
          this.changeVolatilityVal = 20;
          break;
        case 30:
          this.changeVolatility = 2;
          this.changeVolatilityVal = 30;
          break;
        case 50:
          this.changeVolatility = 3;
          this.changeVolatilityVal = 50;
          break;
        case 80:
          this.changeVolatility = 4;
          this.changeVolatilityVal = 80;
          break;
        case 100:
          this.changeVolatility = 5;
          this.changeVolatilityVal = 100;
          break;
        default:
          this.changeVolatility = -1;
          this.changeVolatilityVal = '';
          break;
      }
    },
    // 创建行情提醒
    handleCreateRemind() {
      this.handleFormatNumber();
      if (this.maxPriceVerification || this.minPriceVerification || this.maxPriceVeriError || this.minPriceVeriError) {
        return;
      }

      // TOKEN
      const token = localStorage.getItem('Frontend-Token');
      if (!token) {
        // 获取授权
        this.handleAuthorized(() => {
          this.handleCreateRemind();
        });
        return;
      }

      const statusParams = {
        symbolId: this.symbolId,
        maxPrice: this.maxPrice,
        minPrice: this.minPrice,
        volatility: this.changeVolatilityVal,
      }
      this.$http.post('/account/addMarketRemindRecord', statusParams).then((res) => {
        if (res.code === 401) {
          this.handleAuthorized(() => {
            this.handleCreateRemind();
          });
          return;
        }
        if (res.code === 1015) {
          this.$message.error(this.$t('ndxStake.limitNum'));
        }
        if (res.code !== 0) {
          this.$message.error(this.$t('ndxStake.createError'));
          return;
        }
        this.$message.success(this.$t('ndxStake.createSuccess'));
        // const user = this.$store.state.app.accountInfo;
        // if (user.remainMarketRemindCount > 0) {
        //   user.remainMarketRemindCount -= 1;
        //   user.usedMarketRemindCount += 1;
        // }
        // // 更新vuex accountInfo 值
        // this.$store.dispatch('setAccountInfo', user);
        this.handleGetAccountInfo();
        this.$emit('listenRemind', 'added', false);
      });
    },
    // 更新行情提醒
    handleUpdateRemind() {
      this.handleFormatNumber();
      if (this.maxPriceVerification || this.minPriceVerification || this.maxPriceVeriError || this.minPriceVeriError) {
        return;
      }

      // TOKEN
      const token = localStorage.getItem('Frontend-Token');
      if (!token) {
        // 获取授权
        this.handleAuthorized(() => {
          this.handleUpdateRemind();
        });
        return;
      }

      const statusParams = {
        id: this.accountId,
        symbolId: this.symbolId,
        maxPrice: this.maxPrice,
        minPrice: this.minPrice,
        volatility: this.changeVolatilityVal,
      }
      this.$http.post('/account/modMarketRemindRecord', statusParams).then((res) => {
        if (res.code === 401) {
          this.handleAuthorized(() => {
            this.handleUpdateRemind();
          });
          return;
        }
        if (res.code !== 0) {
          this.$message.error(this.$t('ndxStake.changeError'));
          return;
        }
        this.$message.success(this.$t('ndxStake.changeSuccess'));
        // this.handleGetAccountInfo();
        this.$emit('listenRemind', 'added', false);
      });
    },
    // 获取账号会员信息
    handleGetAccountInfo() {
      const scatter = this.$store.state.app.scatter;
      if (scatter && scatter.identity) {
        const params = {
          account: scatter.identity.accounts[0].name
        }
        this.$http.post('/account/getAccountInfo', params).then((res) => {
          if (res.code === 1007) {
            const info = {
              account: this.$store.state.app.scatter.identity.accounts[0].name,
              chain: this.$store.state.app.scatter.chain,
              ambassadorType: null,
              anonymous: 0,
              consumeLevel: 0,
              discountRate: 1,
              email: null,
              expireTime: null,
              isDealRemind: 0,
              isMarketRemind: 0,
              isRenew: 0,
              joinTime: null,
              language: this.$store.state.app.language,
              level: 0,
              maxLevel: 10,
              ndxStaked: 0,
              noRemindPartial: 0,
              orderTime: null,
              remainDealRemindCount: 10,
              remainDrawCount: 0,
              remainMarketRemindCount: 5,
              renewDuration: null,
              stakeLevel: 0,
              totalSaveAmount: 0,
              usedMarketRemindCount: 0,
              vipImageUrl: null,
              vipMode: 0,
              weight: 0,
              weightRatio: 0,
              remainFreeOrderCount: 1,
            }
            this.$store.dispatch('setAccountInfo', info);
          }
          if (res.code !== 0) {
            return;
          }
          if (res.code === 0) {
            this.$store.dispatch('setAccountInfo', res.accountInfo);
          }
        });
        return;
      }
      this.$store.dispatch('setAccountInfo', {});
    },
    // 价格高于输入框验证
    handleMaxVerification() {
      if (this.maxPrice === '' || this.maxPrice === null) {
        this.maxPriceVerification = false;
        this.maxPriceVeriError = false;
        return;
      }
      if (this.maxPrice < 0) {
        this.maxPriceVeriError = true;
      } else {
        this.maxPriceVeriError = false;
        if (this.maxPrice >= Number(this.symbolPrice)) {
          this.maxPriceVerification = false;
        } else {
          this.maxPriceVerification = true;
        }
      }
    },
    // 价格低于输入框验证
    handleMinVerification() {
      if (this.minPrice === '' || this.minPrice === null) {
        this.minPriceVerification = false;
        this.minPriceVeriError = false;
        return;
      }
      if (this.minPrice < 0) {
        this.minPriceVeriError = true;
      } else {
        this.minPriceVeriError = false;
        if (this.minPrice <= Number(this.symbolPrice)) {
          this.minPriceVerification = false;
        } else {
          this.minPriceVerification = true;
        }
      }
    },
    // 价格精度
    handleFormatNumber() {
      const p = this.priceDecimal; // 价格精度
      if (this.maxPrice && this.maxPrice !== 0) {
        this.maxPrice = toFixed(this.maxPrice, p);
        this.handleMaxVerification();
      }
      if (this.minPrice && this.minPrice !== 0) {
        this.minPrice = toFixed(this.minPrice, p);
        this.handleMinVerification();
      }
    },
    // 点击最新价带入价格
    handleChangePrice() {
      const p = this.priceDecimal; // 价格精度
      this.maxPrice = toFixed(toNonExponential(this.symbolPrice * 1.1), p);
      this.minPrice = toFixed(toNonExponential(this.symbolPrice * 0.9), p);
      this.maxPriceVerification = false;
      this.minPriceVerification = false;
    },
    // 跳转到设置行情提醒列表
    handleToQuotation() {
      this.$router.push({
        name: 'quotation'
      });
    },
    // 跳转到修改邮箱
    handleToChangeEmail() {
      this.$router.push({
        name: 'email'
      });
    },
    // 授权操作
    handleAuthorized(callback) {
      authorized(this, (code, result) => {
        if (code === 'error') { // 授权错误
          console.log(result); // eslint-disable-line
          return;
        }
        callback();
      });
    },
    /*
    * 进度格式化
    * @params numb Number
    * @p 保留小数后几位
    */
    toFixed(numb, p) {
      return toFixed(numb, p);
    },
    // 科学计数法
    toNonExponential(num) {
      return toNonExponential(num);
    },
    parseSymbol(a, b) {
      return parseSymbol(a, b)
    }
  },
}
</script>

<style scoped lang="scss">
$-color: #278EDA;

.noMargin {
  margin: 0 !important;
}
.remindLayer {
  padding: 0 20px;
  color: #333;

  /deep/ .el-input__inner {
    width: 200px !important;
    height: 30px !important;
    line-height: 30px;
    padding-right: 35px;
    margin-left: 5px;
  }

  /deep/ .el-input__suffix {
    line-height: 30px;
    right: 35px;
    font-size: 12px;
    color: #000;
  }

  .remindTitle {
    display: block;
    text-align: center;
    color: #333;
    font-size: 18px;
    margin: -20px auto 0;
  }

  .newPrice {
    font-size: 14px;
    text-align: center;
    margin-top: -20px;
    margin-bottom: 30px;
  }

  .remindPrice {
    margin-bottom: 25px;
    margin-top: 20px;
  }

  .allRemind {
    display: inline-block;
    color: $-color;
    cursor: pointer;
  }

  .allRemind1 {
    display: inline-block;
    color: #333;
    cursor: pointer;
  }

  .hideArrow {
    /deep/ .el-input__inner {
      -moz-appearance: textfield;
      &::-webkit-outer-spin-button,
      &::-webkit-inner-spin-button {
        -webkit-appearance: none;
      }
    }
  }

  .remindMain {
    & > div {
      display: inline-block;
    }

    .contLeft {
      width: 310px;

      .setPrice {
        position: relative;

        label {
          width: 110px;
        }

        .priceTip {
          position: absolute;
          bottom: -19px;
          left: 88px;
          font-size: 12px;
          color: #FF1739;
        }

        .borderRed {
          /deep/ .el-input__inner {
            border-color: #FF1739;
          }
        }
      }

      .setPrice {
        margin-bottom: 25px;
      }
    }

    .contCenter {
      width: 80px;
      padding-top: 5px;
      vertical-align: top;

      .contCenterText {
        display: inline-block;
      }
    }

    .contRight {
      width: 270px;
      vertical-align: top;

      & > div {
        display: inline-block;
        width: 67px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border: 1px solid #bbb;
        color: #000;
        margin-right: 34px;
        margin-bottom: 25px;
        border-radius: 3px;
        cursor: pointer;

        &.active {
          color: $-color;
          border-color: $-color;
        }
      }
    }
  }

  .remindEmail {
    border-top: 1px solid #ECECEC;
    padding: 15px 0;
    margin-top: 10px;

    .changeBtn {
      margin-left: 10px;
      color: $-color;
      cursor: pointer;
    }

    .nobind {
      color: #FF1739;
    }
  }

  .comfirmBtn {
    margin-top: 10px;
    text-align: center;

    p {
      margin: 10px 0;
    }
  }
}
.theme-1B1D27 {
  .remindLayer {
    /deep/ .el-input__suffix,
    .allRemind1,
    .remindMain .contLeft .setPrice label,
    .remindMain .contCenter,
    .remindEmail,
    .comfirmBtn p {
      color: rgba(255, 255, 255, 0.6);
    }
    .remindEmail {
      border-color: rgba(255, 255, 255, 0.1) !important;
    }
  }

  .remindTitle {
    color: rgba(255, 255, 255, 0.6) !important;
  }

  .contRight {
    div {
      color: rgba(255, 255, 255, 0.6) !important;
    }
  }

  .el-button--primary {
    background: #52a5e1;
  }

  .is-disabled{
    background: #4e5b85;
    border-color: #4e5b85;
  }

  .newPrice {
    span {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}
</style>
